#include "uniquedl.h"

UniqueDl::UniqueDl(QObject *parent, QString filePath, QFile *file) :
    QThread(parent), filePath(filePath), file(file)
{
}
#include <QtDebug>
void UniqueDl::run()
{
    http = new QHttp();
    connect(http, SIGNAL(dataReadProgress(int, int)), this, SLOT(downloadProgress(int, int)));
    connect(http, SIGNAL(stateChanged(int)), this, SLOT(stateChange(int)));
    connect(http, SIGNAL(done(bool)), this, SLOT(chargementTermine(bool)));
    http->setHost("l2updater.seobrya.com");
    qDebug() << "start init donwloading" << filePath;
    //QEventLoop loop;
    qDebug() << "try to get: " << filePath;
    http->get(filePath.prepend("/"));
    qDebug() << "wait signal";
    //loop.exec(QEventLoop::AllEvents|QEventLoop::WaitForMoreEvents);
    qDebug() << "end init donwloading" << filePath;
    exec();
}

void UniqueDl::chargementTermine(bool erreur)
{
    if(erreur)
        QMessageBox::information(0, "Erreur", QString::number(http->error()));
    else
    {
        file->write(http->readAll());
    }
    file->close();
    delete file;
    qDebug() << "donwloading done for " << filePath;
    emit done();
}

void UniqueDl::downloadProgress(int un,int deux)
{
     qDebug() << "je dl ce fichier mon capitaine: " << filePath;
    emit updateProgress(un, deux);
}

void UniqueDl::stateChange(int state)
{
    qDebug() << "stateChange:";
    switch (state)
    {
        case 0:
        qDebug() << "unconnected";
        break;
        case 1:
        qDebug() << "Host look up";
        break;
        case 2:
        qDebug() << "connecting";
        break;
        case 3:
        qDebug() << "Sending";
        break;
        case 4:
        qDebug() << "reading";
        break;
        case 5:
        qDebug() << "Connected";
        break;
        case 6:
        qDebug() << "closing";
        break;
    }
}
